import { baseURL } from '@/api/_client.ts';
import { getHomeCarousels, getHomeNavigationIcons } from '@/api/agriculture.ts';
import { defineStore } from 'pinia';
import { ref } from 'vue';

interface Carousel {
  alt: string;
  src: string;
}

export const useImageStore = defineStore(
  'ImageStore',
  () => {
    // 导航栏项目图标
    const image = ref<{ src: string }[]>([]);
    const iconLoading = ref(true);

    const getIcon = () => {
      iconLoading.value = true;
      image.value = [];

      getHomeNavigationIcons()
        .then((v) => {
          const { data } = v;

          if (Array.isArray(data)) {
            const imageUrls = data
              .map((item) => {
                const url = item?.attributes?.icon?.data?.attributes?.formats?.thumbnail?.url;
                return url ? { src: baseURL + url } : null;
              })
              .filter(Boolean);

            image.value = imageUrls as { src: string }[];
          }
        })
        .catch((error) => {
          console.error('获取导航图标失败:', error);
          // 可以在这里添加错误处理逻辑
        })
        .finally(() => {
          iconLoading.value = false;
        });
    };

    // 首页轮播图
    const carousels = ref<Carousel[]>([]);
    const carouselLoading = ref(true);

    const getCarousels = async () => {
      try {
        const res = await getHomeCarousels();
        const { data } = res;
        carousels.value = data.map((item: any) => ({
          alt: item.attributes.alt,
          src: baseURL + `${item.attributes.src.data.attributes.url}`,
        }));
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        carouselLoading.value = false;
      }
    };

    return {
      image,
      iconLoading,
      getIcon,
      carouselLoading,
      carousels,
      getCarousels,
    };
  },
  {
    persist: true,
  }
);
